﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;


namespace CalcEng
{
  public  class HtmlEngine
    {
        public static void UpdateHtmls(string tdwPath, List<CalcResult> cRets)
        {
            string htmlFolder = tdwPath + @"\T0002\export\HTMLs\";
            if (!Directory.Exists(htmlFolder))
            {
                Directory.CreateDirectory(htmlFolder);
            }

            foreach (CalcResult cre in cRets)
            {
                UpdateHtml(tdwPath, cre);
            }
        }

        public static void UpdateHtml(string tdwPath, List<CalcResult> cRets)
        {
            SortedList<string, CalcResult> cretList = new SortedList<string, CalcResult>();
            foreach (CalcResult cre in cRets)
            {
                if (!cretList.ContainsKey(cre.date))
                {
                    cretList.Add(cre.date, cre);
                }
            }

            string htmlFolder = tdwPath + @"\T0002\export\HTMLs\";
            string htmlfile = htmlFolder + cRets[0].code + ".html";
            XmlDocument xmlDoc = new XmlDocument();
            if (File.Exists(htmlfile))
            {
                xmlDoc.Load(htmlfile);
            }
            else
            {
                string htmltemplate = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\template.HTML";
                xmlDoc.Load(htmltemplate);
            }   

            XmlNode root = xmlDoc.FirstChild;
            XmlNode head = root.FirstChild;
            head.FirstChild.InnerText = string.Format("{0} | {1}", cRets[0].code, cRets[0].strName);

            XmlNode body = head.NextSibling;
            XmlNode table = body.FirstChild;

            foreach (CalcResult cre in cretList.Values)
            {
                UpdateCreToXmlNode(cre, ref table);
            }

            XmlTextWriter writer = new XmlTextWriter(htmlfile, Encoding.Unicode);
            writer.Formatting = Formatting.Indented;
            xmlDoc.WriteContentTo(writer);
            // writer.Flush();
            writer.Close();
        }

  

        public static void UpdateHtml(string tdwPath, CalcResult cre)
        {
            string htmlFolder = tdwPath + @"\T0002\export\HTMLs\";
            string htmlfile = htmlFolder + cre.code + ".html";
            XmlDocument xmlDoc = new XmlDocument();
            if (File.Exists(htmlfile))
            {
                xmlDoc.Load(htmlfile);
            }
            else
            {
                string htmltemplate = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + @"\template.HTML";
                xmlDoc.Load(htmltemplate);
            }

            XmlNode root = xmlDoc.FirstChild;
            XmlNode head = root.FirstChild;
            head.FirstChild.InnerText = string.Format("{0} | {1}", cre.code, cre.strName);

            XmlNode body = head.NextSibling;
            XmlNode table = body.FirstChild;
                   
            UpdateCreToXmlNode(cre, ref table);

            XmlTextWriter writer = new XmlTextWriter(htmlfile, Encoding.Unicode);
            writer.Formatting = Formatting.Indented;
            xmlDoc.WriteContentTo(writer);
            // writer.Flush();
            writer.Close();
        }

        private static void SetColorAttribute(XmlNode xmlNode, float p)
        {
            string color;
            if (p > 1.3F)
                color = "green";
            else if (p > 1.15F)
                color = "lawngreen";
            else if (p > 1.0F)
                color = "YellowGreen";
            else if (p > 0.85F)
                color = "gold";
            else if (p > 0.6F)
                color = "brown";
            else if(p < 0.000001F)
                color = "white";
            else
                color = "red";
            xmlNode.Attributes[0].Value = color;
        }

        private static void SetColorAttribute2(XmlNode xmlNode, float p)
        {
            string color;
            if (p > 1.2F)
                color = "green";
            else if (p > 1.1F)
                color = "lawngreen";
            else if (p > 0.95F)
                color = "YellowGreen";
            else if (p > 0.8F)
                color = "gold";
            else if (p > 0.55F)
                color = "brown";
            else if (p < 0.000001F)
                color = "white";
            else
                color = "red";
            xmlNode.Attributes[0].Value = color;
        }

        private static void SetColorAttribute3(XmlNode xmlNode, int volb, int vols)
        {
            if (volb > vols)
                xmlNode.Attributes[0].Value = "lawngreen";
            else if (vols > volb)
                xmlNode.Attributes[0].Value = "brown";
            else
                xmlNode.Attributes[0].Value = "white";
        }

        private static void SetColorAttribute3(XmlNode xmlNode, float percent)
        {
            if (percent < 0.0F)
                xmlNode.Attributes[0].Value = "green";
            else if (percent > 0.0F)
                xmlNode.Attributes[0].Value = "red";
            else
                xmlNode.Attributes[0].Value = "white";
        }

        

        private static void UpdateCreToXmlNode(CalcResult cre, ref XmlNode table)
        {
            XmlNode newtrnode = null;
            int nIdx = 1;
            for(; nIdx < table.ChildNodes.Count; nIdx++)
            {
                XmlNode trnode = table.ChildNodes[nIdx];
                XmlNode dateNode = trnode.FirstChild;
                if (dateNode.InnerText == cre.date)
                {
                    newtrnode = trnode;
                    break;
                }
            }

            float volInc = 0.0F;
            float closeInc = 0.0F;
            float closeInc5 = 0.0F;
            if (nIdx > 1)
            {
                CalcVolCloseInc(table.ChildNodes, nIdx, cre, out volInc, out closeInc, out closeInc5);
            }

            if (newtrnode == null)
            {
                newtrnode = table.FirstChild.CloneNode(true);
                table.AppendChild(newtrnode);               
            }

            newtrnode.ChildNodes[0].InnerText = cre.date;
            
            newtrnode.ChildNodes[1].InnerText = string.Format("{0:f2}", cre.iav);
            SetColorAttribute2(newtrnode.ChildNodes[1], cre.iav);

            newtrnode.ChildNodes[2].InnerText = string.Format("{0:f2}", cre.jav);
            SetColorAttribute(newtrnode.ChildNodes[2], cre.jav);

            newtrnode.ChildNodes[3].InnerText = string.Format("{0:f2}", cre.mav);
            SetColorAttribute(newtrnode.ChildNodes[3], cre.mav);    

            newtrnode.ChildNodes[4].InnerText = string.Format("{0:f2}", cre.weighted);
            SetColorAttribute(newtrnode.ChildNodes[4], cre.weighted);

            newtrnode.ChildNodes[5].InnerText = string.Format("{0}, {1:f1}", cre.vol, volInc);
            SetColorAttribute(newtrnode.ChildNodes[5], volInc);

            newtrnode.ChildNodes[6].InnerText = string.Format("{0:f2}, {1:f2}, {2:f1}", cre.fClosePrice, closeInc, closeInc5);
            SetColorAttribute3(newtrnode.ChildNodes[6], closeInc);

            newtrnode.ChildNodes[7].InnerText = cre.avgvolb.ToString();
            SetColorAttribute3(newtrnode.ChildNodes[7], cre.avgvolb, cre.avgvols);

            newtrnode.ChildNodes[8].InnerText = cre.avgvols.ToString();

            newtrnode.ChildNodes[9].InnerText = cre.avgvolnb.ToString();
            SetColorAttribute3(newtrnode.ChildNodes[9], cre.avgvolns, cre.avgvolnb);

            newtrnode.ChildNodes[10].InnerText = cre.avgvolns.ToString();

            newtrnode.ChildNodes[11].InnerText = cre.bidAM.ToString();

            newtrnode.ChildNodes[12].InnerText = cre.bidPM.ToString();

            XmlNode linknode = newtrnode.ChildNodes[13].FirstChild;
            string filename = Path.GetFileName(cre.dataFile);
            DirectoryInfo dirInfo = new DirectoryInfo(Path.GetDirectoryName(cre.dataFile));
            linknode.Attributes[0].Value = @"..\" + dirInfo.Name + @"\" + filename;
        }

        private static void CalcVolCloseInc(XmlNodeList xmlNodeList, int nIdx, CalcResult cre, out float volInc, out float closeInc, out float closeInc5)
        {
            volInc = 0.0F;
            closeInc = 0.0F;
            closeInc5 = 0.0F;

            float yclose = 0.0F;
            XmlNode trnode = xmlNodeList[nIdx - 1];
            string strtemp = trnode.ChildNodes[6].InnerText.Split(new char[] { ',' })[0];
            if (float.TryParse(strtemp, out yclose))
            {
                closeInc = 100.0F*(cre.fClosePrice - yclose) / yclose;
            }

            
            int yvol = 0;
            int n = 0;
            int i = nIdx - 1; 
            for (; i > Math.Max(nIdx - 6, 0); i--)
            {
                trnode = xmlNodeList[i];
                strtemp = trnode.ChildNodes[5].InnerText.Split(new char[] { ',' })[0];
                int vol = 0;
                if (int.TryParse(strtemp, out vol))
                {
                    yvol += vol;
                    n++;
                }
            }
            yvol = yvol / n;
            volInc = (float)cre.vol / yvol;

            float yclose5 = 0.0F;
            trnode = xmlNodeList[i+1];
            strtemp = trnode.ChildNodes[6].InnerText.Split(new char[] { ',' })[0];
            if (float.TryParse(strtemp, out yclose5))
            {
                closeInc5 = 100.0F * (cre.fClosePrice - yclose5) / yclose5;
            }
        }
    }
}
